package entity_model.json.deserializers;

import com.google.gson.*;
import entity_model.Entity;
import entity_model.Relationship;

import java.lang.reflect.Type;

/**
* Created by nuno-rafael-figueiredo on 13-05-2014.
*/
public class RelationshipDeserializer implements JsonDeserializer<Relationship> {
    @Override
    public Relationship deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();

        JsonElement pivotElement = jsonObject.get("pivot");
        Entity pivot = pivotElement == null ? null : context.deserialize(pivotElement, Entity.class);
        Relationship.Role leftRole = context.deserialize(jsonObject.get("leftRole"), Relationship.Role.class);
        Relationship.Role rightRole = context.deserialize(jsonObject.get("rightRole"), Relationship.Role.class);

        final Relationship relationship = new Relationship(pivot, leftRole, rightRole);

        relationship.getLeftRole().getEntity().add(relationship.getRelated());
        relationship.getRightRole().getEntity().add(relationship.getReversed());

        return relationship;
    }
}
